package com.atguigu.jxc.service.impl;

import com.atguigu.jxc.dao.DamageListDao;
import com.atguigu.jxc.dao.DamageListGoodsDao;
import com.atguigu.jxc.dao.UserDao;
import com.atguigu.jxc.entity.DamageList;
import com.atguigu.jxc.entity.DamageListGoods;
import com.atguigu.jxc.entity.User;
import com.atguigu.jxc.service.DamageListGoodsService;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DamageListGoodsServiceImpl implements DamageListGoodsService {
    @Autowired
    UserDao userDao;
    @Autowired
    DamageListDao damageListDao;
    @Autowired
    DamageListGoodsDao damageListGoodsDao;

    @Override
    public Map<String, Object> goodsList(Integer damageListId) {
        List<DamageListGoods> list=damageListGoodsDao.goodsList(damageListId);
        Map<String ,Object> map=new HashMap<>();
        map.put("rows",list);
        return map;
    }

    @Override
    public Map<String, Object> list(String sTime, String eTime) {
        List<DamageList> list=damageListDao.list(sTime,eTime);
        Map<String ,Object> map=new HashMap<>();
        map.put("rows",list);
        return map;
    }

    @Transactional
    @Override
    public void save(String damageNumber, DamageList damageList, String damageListGoodsStr) {
        List<DamageListGoods> list =null;
        try {
             list=new ObjectMapper().readValue(damageListGoodsStr, new TypeReference<List<DamageListGoods>>() {
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
        User user = userDao.findUserByName((String) SecurityUtils.getSubject().getPrincipal());
        damageList.setUserId(user.getUserId());
        damageList.setDamageNumber(damageNumber);
        damageListDao.insert(damageList);
        Integer damageListId = damageList.getDamageListId();
        for (DamageListGoods damageListGoods : list) {
            damageListGoods.setDamageListId(damageListId);
        }
        damageListGoodsDao.batchInsert(list);
    }
}
